package org.yunai.swjg.server.module.idSequence;

import org.yunai.swjg.server.entity.IdSequenceEntity;
import org.yunai.swjg.server.module.idSequence.persistance.IdSequenceDataUpdater;
import org.yunai.yfserver.persistence.PersistenceObject;
import org.yunai.yfserver.spring.BeanManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * DB ID自增序列
 * User: yunai
 * Date: 13-4-11
 * Time: 下午1:57
 */
public class IdSequence implements PersistenceObject<String, IdSequenceEntity> {

    private static IdSequenceDataUpdater dataUpdater;

    static {
        IdSequence.dataUpdater = BeanManager.getBean(IdSequenceDataUpdater.class);
    }

    private String id;
    private AtomicInteger seq;
    private boolean inDB = false;

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void fromEntity(IdSequenceEntity entity) {
        this.id = entity.getId();
        this.seq = new AtomicInteger(entity.getSeq());
        this.inDB = true;
    }

    @Override
    public IdSequenceEntity toEntity() {
        IdSequenceEntity entity = new IdSequenceEntity();
        entity.setId(id);
        entity.setSeq(seq.get());
        return entity;
    }

    @Override
    public boolean isInDB() {
        return inDB;
    }

    @Override
    public void setInDB(boolean inDB) {
        this.inDB = inDB;
    }

    /**
     * TODO 返回比较尴尬，就先返回0吧
     *
     * @return 0
     */
    @Override
    public Integer getUnitId() {
        return 0;
    }

    public int genSeq() {
        int newSeq = seq.getAndIncrement();
        dataUpdater.addSave(this);
        return newSeq;
    }
}
